$(document).ready(function(){
	var currentPage = 1;
	var pageSize = 10;
	var token = $.zui.store.get("token");
	var userId = $.zui.store.get("userId");
	
	var queryListFun = function(){
		//获取列表数据
		var queryListUrl = adminQueryUrl + devModelService + queryPageListMethod;
		
		var param = "";
		//搜索参数
		if ($("#queryDevModelNameLike").val()!=''){
			param += "queryDevModelNameLike="+$("#queryDevModelNameLike").val();
		}
		if ($("#queryDevFactory").val()!=''){
			param += "&queryDevFactory="+$("#queryDevFactory").val();
		}
		if (currentPage>0){
			param += "&currentPage="+(currentPage-1);
		}
		param += "&pageSize="+pageSize;
		param += "&currentPage="+(currentPage-1);
		
		console.log('queryListUrl='+queryListUrl);
		console.log('token='+token+",userId="+userId);
		console.log('param='+param);
		$.ajax({
			url:queryListUrl,
			type:'post',
			beforeSend:function(xhr){
				xhr.setRequestHeader("token",token);
				xhr.setRequestHeader("userId",userId);
			},
			header:{"token":token,"userId":userId},
			data:param,
			dataType:"JSON",
			success:function(result){
				console.log(result.success);
				console.log(result.pageList);
				if (result.success== '1'){
					document.getElementById("queryDevFactory").options.length=1;
					$.each(result.devFactoryList, function(i, item){ 
						if(item.DevFactory_ID==result.DevFactoryMap.queryDevFactory){
							$("#queryDevFactory").append("<option value='"+item.DevFactory_ID+"' selected='selected'>"+item.DevFactoryName+"</option>");
						}else{
							$("#queryDevFactory").append("<option value='"+item.DevFactory_ID+"'>"+item.DevFactoryName+"</option>");
						}
					});
					$('#listDataGrid').empty();
					$('#listDataGrid').data('zui.datagrid',null);
					$('#listPager').empty();
					$('#listPager').data('zui.pager',null);
					
					$('#listDataGrid').datagrid({
						checkable: true,
					    checkByClickRow: true,
					    selectable: true,
					    dataSource: {
					        cols:[
					        		{name: 'DevModel_ID', label: '主键', width: 0},
					        	 	{name: 'DevModel_Code', label: '型号编码', width: 150},
						            {name: 'DevModelName', label: '型号名称', width: 134},
						            {name: 'DevFactoryName', label: '所属厂商', width: 109},
						            {name: 'SortNo', label: '排序值', width: 200},
						            {name: 'Opr_Date', label: '操作时间', width: -1}
					        ],
					        cache:false,
					        array:result.pageList
					    }
					 
					});	
					$('#listDataGrid').data('zui.datagrid').sortBy('SortNo', 'asc');
					
					// 手动进行初始化
					$('#listPager').pager({
					    page: currentPage,
					    recPerPage:pageSize,
					    elements:['first_icon', 'prev_icon', 'pages', 'next_icon', 'last_icon', 'total_text','size_menu','goto'],
					    pageSizeOptions:[5,10,20,30,50,100],
					    recTotal: result.pageTotal
					});
				}
				else {
					new $.zui.Messager(result.msg, {
					    type: 'warning', // 定义颜色主题
					    placement: 'center' // 定义显示位置
					}).show();
				}
			},
			error:function(result){
				new $.zui.Messager('系统繁忙,请稍候再试!', {
				    type: 'warning', // 定义颜色主题
				    placement: 'center' // 定义显示位置
				}).show();
			}
		});
	};
	//调起查询数据
	queryListFun();
	
	//查询
	$("#searchBtn").click(function(){
		queryListFun();
	});
	//监听分页，修改当前页，条数
	$('#listPager').on('onPageChange', function(e, state, oldState) {
		currentPage = state.page;
		pageSize = state.recPerPage;
		queryListFun();
	});
	//初始化添加
	$("#addBtn").click(function(){
		//获取所属厂商列表
		var url = adminQueryUrl + devModelService +initAddMethod ;
		var param = '';//请求到列表页面
		$("#addForm")[0].reset();
		console.log(url+param);
		$.ajax({
			url:url,
			type:'post',
			dataType:'JSON',
			beforeSend:function(xhr){//设置请求头信息
				xhr.setRequestHeader("token",token);
				xhr.setRequestHeader("userId",userId);
			},
			header:{'token':token,'userId':userId},
			data:param,
			success:function(data){
				console.log(data.menuList)
				if (data.success=='1'){
					document.getElementById("addDevFactory_Code").options.length=1;
					$.each(data.addFactoryList, function(i, item){ 
						$("#addDevFactory_Code").append("<option value='"+item.DevFactory_ID+"'>"+item.DevFactoryName+"</option>");
				});
				}
			},
			error:function(e){
				new $.zui.Messager('系统繁忙,请稍候再试!', {
				    type: 'warning',
				    placement:'center'
				}).show();
			}
		});

		
	});
	
	$("#addSaveBtn").click(function(){
			var validDevModelNameUrl = adminQueryUrl + devModelService + validDevModel ;
			$("#addForm").validate({
				rules:{
					addDevModelName:{
						"required":true,
						"remote":{
							url:validDevModelNameUrl,
							type:'post',
							beforeSend:function(xhr){//设置请求头信息
								xhr.setRequestHeader("token",token);
								xhr.setRequestHeader("userId",userId);
							},
							header:{'token':token,'userId':userId},
							dataType:'json',
							data:{
								'addDevModelName':function(){
									return $("#addDevModelName").val();
								}
							}
						}
					},
					addDevFactory_Code:{
						"required":true
					},
					addSortNo:{
						"required":true
					}
					
				},
				messages:{
					addDevModelName:{
						"required":"请输入设备型号名称！",
						"remote":"该设备型号名称已经存在！"
					},
					addDevFactory_Code:{
						"required":"请选择设备所属厂商！"
					},
					addSortNo:{
						"required":"请输入排序值"
					}
				},
				submitHandler:function(form){
					console.log("xx:"+adminQueryUrl +  devModelService + addMethod);
					
					$.ajax({
						url:adminQueryUrl + devModelService + addMethod ,
						type:'post',
						dataType:'JSON',
						beforeSend:function(xhr){//设置请求头信息
							xhr.setRequestHeader("token",token);
							xhr.setRequestHeader("userId",userId);
						},
						header:{'token':token,'userId':userId},
						data:$(form).serialize(),
						success:function(data){
							console.log('添加data='+data);
							if (data.success == '1') {
			                	new $.zui.Messager('添加成功!', {
			    				    type: 'success',
			    				    placement:'center'
			    				}).show();
			                	queryListFun();
			                	$('#addModal').modal('hide', 'fit');
			                }
			                else{
			                	new $.zui.Messager(data.msg, {
			    				    type: 'warning',
			    				    placement:'center'
			    				}).show();
			                }
						},
						error:function(e){
							new $.zui.Messager('系统繁忙,请稍候再试!', {
		    				    type: 'warning',
		    				    placement:'center'
		    				}).show();
						}
					});
				}
			});	
	    });
	//初始化修改
	$("#updateBtn").click(function(){
		// 获取数据表格实例
		var listDataGrid = $('#listDataGrid').data('zui.datagrid');
		// 获取当前已选中的行数据项
		var selectedItems = listDataGrid.getCheckItems();
		if (selectedItems.length == 0) {
			new $.zui.Messager('请选择要修改的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else if (selectedItems.length > 1) {
			new $.zui.Messager('请只选择一条要修改的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else {
			$("#updateForm")[0].reset();
			var url = adminQueryUrl + devModelService +initUpdateMethod;
			var param = 'DevModelId='+selectedItems[0].DevModel_ID;
			console.log('param='+param);
			$.ajax({
				url:url,
				type:'post',
				dataType:'JSON',
				beforeSend:function(xhr){//设置请求头信息
					xhr.setRequestHeader("token",token);
					xhr.setRequestHeader("userId",userId);
				},
				headers:{'token':token,'userId':userId},
				data:param,
				success:function(data){
					console.log('初始化修改data='+data);
					console.log(data.devFactoryList);
					if (data.success=='1'){
						$("#updateDevModel_Code").val(data.devModelMap.DevModel_Code);
						$("#updateDevModelName").val(data.devModelMap.DevModelName);
						$.each(data.devFactoryList, function(i, item){ 
							if(item.DevFactory_ID==data.devModelMap.DevFactory_Code){
								console.log(item.DevFactory_Code+'---'+data.devModelMap.DevFactory_Code);
								$("#updateDevFactory_Code").append("<option value='"+item.DevFactory_ID+"' selected='selected'>"+item.DevFactoryName+"</option>");
							}else{
								$("#updateDevFactory_Code").append("<option value='"+item.DevFactory_ID+"'>"+item.DevFactoryName+"</option>");
							}
						});
						$("#updateRemark").val(data.devModelMap.Remark);
						$("#updateSortNo").val(data.devModelMap.SortNo);
					}
				},
				error:function(e){
					new $.zui.Messager('系统繁忙,请稍候再试!', {
					    type: 'warning',
					    placement:'center'
					}).show();
				}
			});
		}
	});
	//修改保存
	$("#updateSaveBtn").click(function(){
		var excludeDevModelId = $('#listDataGrid').data('zui.datagrid').getCheckItems()[0].DevModel_ID;
		console.log("修改保存的ID"+excludeDevModelId);
		var validDevModelNameUrl = adminQueryUrl + devModelService + validDevModel;
		$("#updateForm").validate({
			rules:{
				updateDevModelName:{
					"required":true,
					"remote":{
						url:validDevModelNameUrl,
						type:'post',
						beforeSend:function(xhr){//设置请求头信息
							xhr.setRequestHeader("token",token);
							xhr.setRequestHeader("userId",userId);
						},
						header:{'token':token,'userId':userId},
						dataType:'json',
						data:{
							'updateDevModelName':function(){
								return $("#updateDevModelName").val();
							},
							'excludeDevModelId':function(){
								return excludeDevModelId;
							}
						}
					}
				},
				updateDevFactory_Code:{
					"required":true
				},
				updateSortNo:{
					"required":true
				}
				
			},
			messages:{
				updateDevModelName:{
					"required":"请输入设备型号名称！",
					"remote":"该设备型号名称已经存在！"
				},
				updateDevFactory_Code:{
					"required":"请选择设备所属厂商！"
				},
				updateSortNo:{
					"required":"请输入排序值"
				}
			},
			submitHandler:function(form){
				var saveUrl = adminQueryUrl + devModelService + updateMethod;
				$.ajax({
					url:saveUrl,
					type:'post',
					dataType:'JSON',
					beforeSend:function(xhr){//设置请求头信息
						xhr.setRequestHeader("token",token);
						xhr.setRequestHeader("userId",userId);
					},
					header:{'token':token,'userId':userId},
					data:$(form).serialize()+"&excludeDevModelId="+excludeDevModelId,
					success:function(data){
						console.log('data='+data);
						if (data.success == '1') {
		                	new $.zui.Messager('修改成功!', {
		    				    type: 'success',
		    				    placement:'center'
		    				}).show();
		                	queryListFun();
		                	$('#updateModal').modal('hide', 'fit');
		                	queryListFun();
		                }
		                else{
		                	new $.zui.Messager(data.msg, {
		    				    type: 'warning',
		    				    placement:'center'
		    				}).show();
		                }
					},
					error:function(e){
						new $.zui.Messager('系统繁忙,请稍候再试!', {
	    				    type: 'warning',
	    				    placement:'center'
	    				}).show();
					}
				});
			}
		});
	});
	//显示删除确认框
	$("#deleteBtn").click(function(){
		// 获取数据表格实例
		var listDataGrid = $('#listDataGrid').data('zui.datagrid');
		// 获取当前已选中的行数据项
		var selectedItems = listDataGrid.getCheckItems();
		if (selectedItems.length == 0) {
			new $.zui.Messager('请选择要删除的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else if (selectedItems.length > 1) {
			new $.zui.Messager('请只选择一条要删除的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else {
			$('#deleteModal').modal('show', 'fit');
		}
	});
	//删除菜单
	$("#deleteDevModelBtn").click(function(){
		// 获取数据表格实例
		var listDataGrid = $('#listDataGrid').data('zui.datagrid');
		// 获取当前已选中的行数据项
		var selectedItems = listDataGrid.getCheckItems();
		var url = adminQueryUrl + devModelService + deleteMethod;
		var param = 'DevModel_ID='+selectedItems[0].DevModel_ID;//请求到列表页面
		console.log('url='+url);
		console.log('param2='+param);
		$.ajax({
			url:url,
			type:'post',
			dataType:'JSON',
			beforeSend:function(xhr){//设置请求头信息
				xhr.setRequestHeader("token",token);
				xhr.setRequestHeader("userId",userId);
			},
			header:{'token':token,'userId':userId},
			data:param,
			success:function(data){
				console.log('data='+data);
				$('#deleteModal').modal('hide', 'fit');
				if (data.success=='1'){
	                	new $.zui.Messager('删除成功!', {
	    				    type: 'success',
	    				    placement:'center'
	    				}).show();
	                	queryListFun();
				}
                else{
                	new $.zui.Messager(data.msg, {
    				    type: 'warning',
    				    placement:'center'
    				}).show();
				}
			},
			error:function(e){
				new $.zui.Messager('系统繁忙,请稍候再试!', {
				    type: 'warning',
				    placement:'center'
				}).show();
			}
		});
	});
	//初始化详情
	$("#detailBtn").click(function(){
		// 获取数据表格实例
		var listDataGrid = $('#listDataGrid').data('zui.datagrid');
		// 获取当前已选中的行数据项
		var selectedItems = listDataGrid.getCheckItems();
		if (selectedItems.length == 0) {
			new $.zui.Messager('请选择要查看的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else if (selectedItems.length > 1) {
			new $.zui.Messager('请只选择一条要查看的记录', {
			    type: 'warning',
			    placement:'center'
			}).show();
		}
		else {
			$("#detailForm")[0].reset();
			var url = adminQueryUrl + devModelService + detailMethod;
			var param = 'DevModelId='+selectedItems[0].DevModel_ID;//请求到列表页面
			console.log('详情param='+param);
			$.ajax({
				url:url,
				type:'post',
				dataType:'JSON',
				beforeSend:function(xhr){//设置请求头信息
					xhr.setRequestHeader("token",token);
					xhr.setRequestHeader("userId",userId);
				},
				header:{'token':token,'userId':userId},
				data:param,
				success:function(data){
					console.log('详情data='+data);
					if (data.success=='1'){
						$("#detailDevModel_Code").val(data.devModelMap.DevModel_Code);
						$("#detailDevModelName").val(data.devModelMap.DevModelName);
						$.each(data.devFactoryList, function(i, item){ 
							if(item.DevFactory_ID==data.devModelMap.DevFactory_Code){
								console.log(item.DevFactory_Code+'---'+data.devModelMap.DevFactory_Code);
								$("#detailDevFactory_Code").val(item.DevFactoryName);
							}
						});
						$("#detailRemark").val(data.devModelMap.Remark);
						$("#detailSortNo").val(data.devModelMap.SortNo);
						$("#Opr_id").val(data.devModelMap.Opr_id);
						$("#Opr_Date").val(data.devModelMap.Opr_Date);
						
					}
				},
				error:function(e){
					new $.zui.Messager('系统繁忙,请稍候再试!', {
					    type: 'warning',
					    placement:'center'
					}).show();
				}
			});
		}
	});
});